/**
 * Project Name:fastPlat
 * File Name:ArticleController.java
 * Package Name:com.fast.cms.web.controller.article
 * Date:2014年12月17日下午4:07:54
 * Copyright (c) 2014, lsflu@126.com All Rights Reserved.
 *
 */

package com.fast.cms.web.controller.article;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.fast.base.db.page.PageView;
import com.fast.base.model.AnoSysLog;
import com.fast.base.util.ChineseSpelling;
import com.fast.base.util.LogUtils;
import com.fast.base.util.data.MathUtils;
import com.fast.base.util.web.ResponseData;
import com.fast.base.util.web.ResponseEnum;
import com.fast.base.web.BaseController;
import com.fast.cms.model.article.Article;
import com.fast.cms.model.system.Dictionary;
import com.fast.cms.service.article.ArticleService;
import com.fast.cms.service.system.DictionaryService;
import com.fast.cms.web.form.ArticleListForm;
import com.fast.cms.web.form.CheckArticleForm;
import com.fast.common.userCache.AdminCacheUtils;
import com.fast.common.userCache.UserRequestUtils;
import com.fast.user.model.admin.AdminUser;

/**
 * ClassName:ArticleController <br/>
 * 用途: 文章控制类 <br/>
 * 开发人员：lushuifa  http://lushuifa.iteye.com/
 * 邮箱:lsflu@126.com
 * @version  
 * @since    JDK 1.6
 * @see
 * Date:     2014年12月17日 下午4:07:54 <br/> 	 
 */
@Controller
@RequestMapping("/article")
public class ArticleController extends BaseController{
	
	private Log log = LogFactory.getLog(ArticleController.class);
	
	@Resource(name="articleService")
	private ArticleService articleService;
	
	@Resource(name="dictionaryService")
	private DictionaryService dictionaryService;
	
	/**
	 * 审批资讯文章
	 * @param checkArticleForm
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/checkArticle.do")
	public ResponseData checkArticle(CheckArticleForm checkArticleForm){
		AdminUser curAdminUser = AdminCacheUtils.getLoginAdminUser();
		ResponseData j = new ResponseData();
		if(curAdminUser!=null){
			int checkerId = curAdminUser.getId();
			String checker = curAdminUser.getRealName();
			checkArticleForm.setCheckerId(checkerId);
			checkArticleForm.setChecker(checker);
			boolean actionFlag = this.articleService.checkArticle(checkArticleForm);
			if(actionFlag){
				//审核机关操作 审核通过时则应该扣除库存
				j.buildSuccessResponse();
			}else{
				j.setCode("01");
				j.setMsg("操作失败,请重试或者重新登录试试！");
			}
		}else{
			j.setCode("01");
			j.setMsg("请先登录再操作！");
		}
		return j;
	}
	
	/**
	 * 加载表单数据
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/batchGenAllArticleHtmlPage.do")
	public ResponseData batchGenAllArticleHtmlPage(){
		ResponseData responseData = new ResponseData();
		this.articleService.batchGeAllArticleHtmlPage();
		responseData.setMsg("进程大约5分钟，请五分钟后再点击相关页面！");
		return responseData;
	}
	
	/**
	 * 将所有资讯生成静态页面
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/increaseReadCount.out")
	public ResponseData increaseReadCount(int id){
		ResponseData responseData = new ResponseData();
		if(id>0){
			this.articleService.updateReadCount(id);
		}
		responseData.setMsg("给【"+id+"】文章记数成功 ！");
		return responseData;
	}
	
	/**
	 * 抓取数据
	 * @param id
	 * @return
	 */
	@AnoSysLog(actionName="远程抓取数据")
	@ResponseBody
	@RequestMapping("/grabArticle.do")
	public ResponseData grabArticleFromUrl(){
		ResponseData responseData = new ResponseData();
		try {
			Thread daoruThread = new Thread(){
				public void run() {
					//articleService.daoruArticleForUrl();
				};
			};
			daoruThread.start();
			responseData.setCode("00");
			responseData.setMsg("远程抓取数据成功！");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("远程抓取数据页面失败！错误："+e.getMessage());
		}
		return responseData;
	}
	
	/**
	 * 查询资讯列表
	 * @param articleTypeId 文章类型ID
	 * @param limitSize
	 * @param selectType
	 * @return
	 */
	@ResponseBody
	@RequestMapping({"/getArticleListForLimit.do","/getArticleListForLimit.out"})
	public ResponseData getArticleListForLimit(String articleTypeId,int limitSize,String selectType){
		ResponseData responseData = new ResponseData();
		try{
			List<Map<String, Object>> articleList = this.articleService.getArticleListForLimit(articleTypeId, limitSize, selectType);
			responseData.setData(articleList);
		}catch(Exception e){
			e.printStackTrace();
			responseData.failue();
		}
 		return responseData;
	}
	
	/**
	 * 编辑[Article]信息
	 * @param imageUrl
	 * @return
	 */
	@RequestMapping("/editArticle.do")
	@ResponseBody
	@AnoSysLog(actionName="编辑发布资讯信息")
	public ResponseData editArticle(@RequestParam MultipartFile imageUrl,@RequestParam MultipartFile attachFile){
		String uuid = webUtil.getString("uuid");
		if(uuid.equals("")){
			uuid = MathUtils.getTheOnlyStr();
		}
		ResponseData responseData = new ResponseData();
		String imageUrlsPath = "";
		if(!imageUrl.isEmpty()&&imageUrl.getSize()>0){
			String savePath = super.getFileDiskPath()+"articleImage/";
			String fileName = uuid+ChineseSpelling.getSpell(imageUrl.getOriginalFilename());
		    imageUrlsPath = "articleImage/"+fileName;
			responseData = super.uploadSingleImgFile(imageUrl,savePath,fileName);
		}
		
		
		String attachFilePath = "";
		if(!attachFile.isEmpty()&&attachFile.getSize()>0){
			try {
				String savePath = super.getFileDiskPath()+"doc/";
				String fileName = uuid+ChineseSpelling.getSpell(attachFile.getOriginalFilename());
				attachFilePath = "doc/"+fileName;
			    FileUtils.copyInputStreamToFile(attachFile.getInputStream(), new File(savePath,fileName));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		/**
		 * 编辑数据
		 */
		if(responseData.getCode().equals("00")){
			Article article = null;
			try {
				int id = webUtil.getInt("id");
				if(id>0){
					article = this.articleService.getById(Article.class,id);
					article = (Article) webUtil.bindDataToBean(article);
					if(!imageUrl.isEmpty()){
						article.setImageUrl(imageUrlsPath);
					}
					if(!attachFile.isEmpty()){
						article.setAttachFilePath(attachFilePath);
					}
				}else{
					article = new Article();
					article = (Article) webUtil.bindDataToBean(article);
					article.setUuid(uuid);
					UserRequestUtils.bindCreaterInfo(article);
					article.setImageUrl(imageUrlsPath);
					article.setAttachFilePath(attachFilePath);
				}
				String articleTypeId = webUtil.getString("articleTypeId");
				
				//当存在UUID时的处理
				if(!articleTypeId.equals("")){
					Dictionary dic = this.articleService.queryForBean(Dictionary.class, " where uuid='"+article.getArticleTypeId()+"'");
					article.setArticleTypeId(articleTypeId);
					article.setArticleType(dic.getDicname());
					String columnDir = this.dictionaryService.getDicDir(dic.getDicname(), dic.getParentUUID());
					article.setColumnDir(columnDir);
					article.setArticleType(dic.getDicname());
					article.setColumnId(dic.getParentUUID());
					article.setColumnName(dic.getParentName());
				}
				UserRequestUtils.bindEditorInfo(article);
				if(null!=this.articleService.saveOrUpdateArticle(article)){
					//生成静态页面
					//this.articleService.genArticleDetailHtmlPage(article);
					responseData.setMsg("编辑编号为["+article.getUuid()+"]操作成功");
				}
				responseData.setCode("00");
			} catch (Exception e) {
				e.printStackTrace();
				responseData.setCode("01");
				responseData.setMsg("编辑编号为["+article.getUuid()+"]操作失败");
			}
		}
		return responseData;
	}
	
	/**
	 * 删除[Article]信息到回收站
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delArticleByIdForHS.do")
	@AnoSysLog(actionName="删除资讯到回收站")
	public ResponseData delArticleByIdForHS(int id) {
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = articleService.deleteByIdForHS(Article.class, id);
			responseData.setCode(actionFlag?"00":"01");
			if(actionFlag){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	
	/**
	 * 删除多个[Article]信息到回站
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/batchDelArticleForHS.do")
	@AnoSysLog(actionName="批量删除文章到回收站")
	public ResponseData batchDelArticleForHS(String ids){
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = articleService.batchDeleteByIdsForHS(Article.class, ids);
			responseData.setCode(actionFlag?"00":"01");
			if(actionFlag){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	@ResponseBody
	@RequestMapping("/batchRebackData.do")
	@AnoSysLog(actionName="批量恢复已删除的数据")
	public ResponseData batchRebackData(String ids){
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = articleService.batchRebackDeleteData(Article.class, ids);
			responseData.setCode(actionFlag?"00":"01");
			if(actionFlag){
				responseData.setMsg("你选中的数据恢复数据成功");
			}else{
				responseData.setMsg("你选中的数据恢复数据失败,请与管理员联系！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}

	/**
	 * 删除[Article]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delArticleById.do")
	@AnoSysLog(actionName="彻底删除某个资讯")
	public ResponseData delArticleById(int id) {
		ResponseData responseData = new ResponseData();
		try {
			//删除对应的图片
			Article article = this.articleService.queryForBean(Article.class, " where id="+id+"");
			if(!article.getImageUrl().equals("")&&article.getImageUrl()!=null){
				String filePath = super.getFileDiskPath()+""+article.getImageUrl();
				File file = new File(filePath);
				if(file.exists()){
					FileUtils.forceDelete(file);
				}
			}
			boolean actionFlag = articleService.deleteById(Article.class, id);
			responseData.setCode(actionFlag?"00":"01");
			if(actionFlag){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.buildResult(ResponseEnum.DELETE_FAILUE);
		}
		return responseData;
	}
	
	/**
	 * 删除多个[Article]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/batchDelArticle.do")
	@AnoSysLog(actionName="批量删除文章")
	public ResponseData batchDelArticle(String ids){
		ResponseData responseData = new ResponseData();
		try {
			int actionCount = articleService.deleteByIds(Article.class, ids);
			responseData.setCode("00");
			responseData.setMsg("删除[资讯]编号为["+ids+"]操作成功,共成功["+actionCount+"]");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("删除[资讯]["+ids+"]操作失败");
		}
		return responseData;
	}
	
	/**
	 * 得到[Article]列表
	 * @return PageView<Article>
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping("/getArticleList.do")
	public Map<String,Object> getArticleList(ArticleListForm articleListForm){
		LogUtils.info("getArticleList param:"+articleListForm.toString());
		PageView<Article> pageView = null;
		Map<String,Object> gridMap = new HashMap<String,Object>();
		try {
			articleListForm.setCurUserId(AdminCacheUtils.getLoginAdminUser().getId()+"");
			pageView = this.articleService.getArticleList(articleListForm);
			gridMap.put("total", pageView.getTotalRecord());
			gridMap.put("rows", pageView.getRecords());
		} catch (Exception e) {
			LogUtils.error("getArticleList err:",e);
		}
		LogUtils.info("getArticleList result:"+pageView.toString());
 		return gridMap;
	}
	
	/**
	 * 得到[Article]列表
	 * @return PageView<Article>
	 * @throws IOException 
	 */
	@RequestMapping("/front/getArticleList.out")
	public ModelAndView getArticleListForFront(ArticleListForm articleListForm){
		ModelAndView modelView = new ModelAndView();
		LogUtils.info("getArticleList param:"+articleListForm.toString());
		PageView<Article> pageView = null;
		try {
			pageView = this.articleService.getArticleList(articleListForm);
			LogUtils.info("getArticleList result:"+pageView.toString());
			modelView.addObject("pageView", pageView);
			//查出导航数据
			String navTypeId = "201503121734568313223";
			List<Map<String, Object>> navList = this.dictionaryService.getDicTreeList(navTypeId);
			modelView.addObject("navList", navList);
			LogUtils.info("navList:"+navList);
			//查询出二级分类数据
			String articleTypeObj = articleListForm.getArticleTypeObj();
			String secondTypeParentId = "";
			if(!StringUtils.isEmpty(articleTypeObj)){
				JSONObject typeJson = JSONObject.parseObject(articleTypeObj.replace("&quot;", "\""));
				secondTypeParentId = typeJson.getString("code");
			}
			if(StringUtils.isEmpty(secondTypeParentId)){
				secondTypeParentId = "201503121734568313223";
			}
			List<Map<String, Object>> secondTypeList = this.dictionaryService.getDicTreeList(secondTypeParentId);
			modelView.addObject("secondTypeList", secondTypeList);
			LogUtils.info("secondTypeList:"+secondTypeList);
			modelView.setViewName("front/articleList.jsp");
		} catch (Exception e) {
			LogUtils.error("getArticleList err:",e);
		}
		LogUtils.info("getArticleList result:"+pageView.toString());
		modelView.addObject("pageView", pageView);
		
		//查出导航数据
		String navTypeId = "201503121734568313223";
		List<Map<String, Object>> navList = this.dictionaryService.getDicTreeList(navTypeId);
		modelView.addObject("navList", navList);
		LogUtils.info("navList:"+navList);
		//查询出二级分类数据
		String secondTypeParentId = articleListForm.getArticleTypeId();
		if(StringUtils.isEmpty(secondTypeParentId)){
			secondTypeParentId = "201503121734568313223";
		}
		
		int count = this.articleService.count(Dictionary.class, "where parentUUID='"+secondTypeParentId+"'");
		if(count<1){
			Dictionary dic = this.dictionaryService.queryForBean(Dictionary.class, "where uuid='"+secondTypeParentId+"'");
			secondTypeParentId = dic.getParentUUID();
		}
		
		List<Map<String, Object>> secondTypeList = this.dictionaryService.getDicTreeList(secondTypeParentId);
		modelView.addObject("secondTypeList", secondTypeList);
		//判断本次查询的长度，如果为1则直接进入详情页
	    if(pageView.getTotalRecord()==1){
	    	modelView.addObject("article",pageView.getRecords().get(0));
	    	modelView.setViewName("/front/articleDetail.jsp");
	    }else{
	    	LogUtils.info("secondTypeList:"+secondTypeList);
			modelView.setViewName("front/articleList.jsp");
	    }
 		return modelView;
	}
	
	
	/**
	 * 获取资讯详情
	 */
	@ResponseBody
	@RequestMapping("/js/getArticleDetail.do")
	@AnoSysLog(actionName="获取资讯详情")
	public ResponseData getAjaxArticleDetail(int id) {
		LogUtils.info("getAjaxArticleDetail is comming!");
		ResponseData responseData = new ResponseData();
		try {
			Article article = articleService.getById(Article.class,id);
			responseData.setData(article);
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.info("获取资讯详情getAjaxArticleDetail err",e);
			responseData.failue();
		}
		return responseData;
	}
	
	
	
	/**
	 * 查询详情
	 * @param id
	 * @return
	 */
	@RequestMapping(path={"/getArticleDetail.do","/front/getArticleDetail.out"})
	public ModelAndView getArticleDetail(@RequestParam(required=true) int id) {
		ModelAndView mv = new ModelAndView();
		Article bean = articleService.queryForBeanById(Article.class, id);
		try {
			mv.addObject("article",bean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String actionType = webUtil.getString("actionType");
		switch (actionType) {
			case "update":
				mv.setViewName("/adminMain/article/article-add.jsp");
				break;
			case "front":
				mv.setViewName("/front/articleDetail.jsp");
				//查出导航数据
				String navTypeId = "201503121734568313223";
				List<Map<String, Object>> navList = this.dictionaryService.getDicTreeList(navTypeId);
				mv.addObject("navList", navList);
				LogUtils.info("navList:"+navList);
				//查询出二级分类数据
				//查询出二级分类数据
				String secondTypeParentId = bean.getArticleTypeId();
				if(StringUtils.isEmpty(secondTypeParentId)){
					secondTypeParentId = "201503121734568313223";
				}
				
				int count = this.articleService.count(Dictionary.class, "where parentUUID='"+secondTypeParentId+"'");
				if(count<1){
					Dictionary dic = this.dictionaryService.queryForBean(Dictionary.class, "where uuid='"+secondTypeParentId+"'");
					secondTypeParentId = dic.getParentUUID();
				}
				
				List<Map<String, Object>> secondTypeList = this.dictionaryService.getDicTreeList(secondTypeParentId);
				mv.addObject("secondTypeList", secondTypeList);
				LogUtils.info("secondTypeList:"+secondTypeList);
				break;
			default:
				mv.setViewName("/manage/article/articleDetail.jsp");
				break;
		}
		return mv;
	}
}

